<?php $this->layout='main' ?>
<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/scriptbreaker-multiple-accordion-1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	$("#sub-nav").accordion({
		accordion:false,
		speed: 300,
		closedSign: '',
		openedSign: ''
	});
});
</script>
<script>
var STATUS = {COMMITTED:1, CHANGED:0};
var DOMAIN = {DETAIL:0, PROFILE:1, TANK:2};
var sitedetailStatus=STATUS.COMMITTED;
var siteprofileStatus=STATUS.COMMITTED;
var tankStatus=STATUS.COMMITTED;

var previousSiteID=0;
var previousTankID=0;

function changeFocus(element)
{
	var elementList=$("[name='tabs']");
	for(var i=0;i<elementList.length;i++)
	{
		if(elementList[i]==element.parentNode)//activate it
		{	
			elementList[i].className="sd"+(i+1)+" sd-active"+(i+1);
		}
		else
		{
			elementList[i].className="sd"+(i+1);
		}
	}
}

function displayProfile(element)
{
	changeFocus(element);
	var profileArea = document.getElementById('site-profile-area');
	var racknetworkArea = document.getElementById('racknetwork-area');
	var sitedetailsArea = document.getElementById('sitedetails-area');
	profileArea.style.display='block';
	racknetworkArea.style.display='none';
	sitedetailsArea.style.display='none';
}

function displayRackNetwork(element)
{
	changeFocus(element);
	var profileArea = document.getElementById('site-profile-area');
	var racknetworkArea = document.getElementById('racknetwork-area');
	var sitedetailsArea = document.getElementById('sitedetails-area');
	profileArea.style.display='none';
	racknetworkArea.style.display='block';
	sitedetailsArea.style.display='none';
}

function displaySiteDetails(element)
{
	changeFocus(element);
	var profileArea = document.getElementById('site-profile-area');
	var racknetworkArea = document.getElementById('racknetwork-area');
	var sitedetailsArea = document.getElementById('sitedetails-area');
	profileArea.style.display='none';
	racknetworkArea.style.display='none';
	sitedetailsArea.style.display='block';
}

/*
* flag: if displaying tank area
*/
function displayTank(flag)
{
	var profileArea = document.getElementById('site-profile-area');
	if(profileArea.style.display=='block')
	{
		var tankArea = document.getElementById('tank-area');
		if(flag)
		{
			tankArea.style.display='block';
		}
		else
		{
			tankArea.style.display='none';
		}
	}
}

/*
* fill site info to the corresponding fields
* including both profile and details areas
*/
function fillSiteInfo(site, tools)
{
	var prefix = '<?php echo get_class(Sites::model()).'_'; ?>';
	
	//site-profile
	var site_name = document.getElementById(prefix+'site_name');//site name
	var address1 = document.getElementById(prefix+'address1');
	var address2 = document.getElementById(prefix+'address2');
	var city = document.getElementById(prefix+'city');
	var state = document.getElementById(prefix+'state');
	var zip = document.getElementById(prefix+'zip');
	var home_rack = document.getElementById(prefix+'home_rack_ID');
	site_name.value = site.site_name;
	address1.value = site.address1;
	address2.value = site.address2;
	city.value = site.city;

	for(var i=0;i<state.options.length;i++)
	{
		if(state.options[i].value==site.state)
		{
			state.selectedIndex = i;
			break;
		}
	}
	
	zip.value = site.zip;
	
	for(var i=0;i<home_rack.options.length;i++)
	{
		if(home_rack.options[i].value==site.home_rack_ID)
		{
			home_rack.selectedIndex = i;
			break;
		}
	}
	
	//site-details
	var contact_name = document.getElementById(prefix+'contact_name');
	var contact_cell_number = document.getElementById(prefix+'contact_cell_number');
	var phone_number_of_site = document.getElementById(prefix+'phone_number_of_site');
	var after_hour_number = document.getElementById(prefix+'after_hour_number');
	var gated = document.getElementById(prefix+'gated');
	var gate_opens = document.getElementById(prefix+'gate_opens');
	var gate_closes = document.getElementById(prefix+'gate_closes');
	var security_on_premises = document.getElementById(prefix+'security_on_premises');
	var security_code = document.getElementById(prefix+'security_code');
	var open_time = document.getElementById(prefix+'open_time');
	var close_time = document.getElementById(prefix+'close_time');
	var directions = document.getElementById(prefix+'directions');
	var notes = document.getElementById(prefix+'notes');
	contact_name.value = site.contact_name;
	contact_cell_number.value = site.contact_cell_number;
	phone_number_of_site.value = site.phone_number_of_site;
	after_hour_number.value = site.after_hour_number;
	for(var i=0;i<gated.options.length;i++)
	{
		if(gated.options[i].value==site.gated)
			gated.selectedIndex = i;
	}
	gate_opens.value = site.gate_opens.substring(0,5);
	gate_closes.value = site.gate_closes.substring(0,5);
	for(var i=0;i<security_on_premises.options.length;i++)
	{
		if(security_on_premises.options[i].value==site.security_on_premises)
			security_on_premises.selectedIndex = i;
	}
	security_code.value = site.security_code;
	open_time.value = site.open_time.substring(0,5);
	close_time.value = site.close_time.substring(0,5);
	directions.value = site.directions;
	notes.value = site.notes;
	//load the tools info
	var elements=document.getElementsByName('tools[]');
	for(var i=0;i<elements.length;i++)
	{
		var flag = false;
		for(var j=0;j<tools.length;j++)
		{
			if(elements[i].id==tools[j].tool_name)
			{
				elements[i].selectedIndex=0;
				flag=true;
				break;
			}
		}
		if(!flag)
			elements[i].selectedIndex = 1;
	}
}

/*
* fill tank info to the corresponding fields
*/
function fillTankInfo(tank, tankMonitor, tank_models, products, productCategory)
{
	var prefix = '<?php echo get_class(Tanks::model()).'_'; ?>';
	var tank_ID = document.getElementById(prefix+'tank_ID');//tank ID
	var site_ID = document.getElementById(prefix+'site_ID');//site_ID
	var tank_name = document.getElementById(prefix+'tank_name');
	var product_ID = document.getElementById(prefix+'product_ID');
	var capacity = document.getElementById(prefix+'capacity');
	var tank_type_ID = document.getElementById(prefix+'tank_type_ID');
	var tank_position_ID = document.getElementById(prefix+'tank_position_ID');
	var tank_monitor_ID = document.getElementById(prefix+'tank_monitor_ID');
	var tank_monitor_mfg= document.getElementById('TankMonitors_monitor_MFG');
	var remote_fill= document.getElementById(prefix+'remote_fill');
	var pump_provided= document.getElementById(prefix+'pump_provided');
	var overfill_alarm= document.getElementById(prefix+'overfill_alarm');
	var product_ID = document.getElementById(prefix+'product_ID');
	var product_category = document.getElementById('product_category');
	
	tank_ID.value=tank.tank_ID;
	site_ID.value=tank.site_ID;
	tank_name.value=tank.tank_name;
	capacity.value=tank.capacity;
	for(var i=0;i<product_ID.options.length;i++)
	{
		if(product_ID.options[i].value==tank.product_ID)
			product_ID.selectedIndex=i;
	}
	for(var i=0;i<tank_type_ID.options.length;i++)
	{
		if(tank_type_ID.options[i].value==tank.tank_type_ID)
			tank_type_ID.selectedIndex=i;
	}
	for(var i=0;i<tank_position_ID.options.length;i++)
	{
		if(tank_position_ID.options[i].value==tank.tank_position_ID)
			tank_position_ID.selectedIndex=i;
	}
	if(tank.tank_monitor_ID==null)
		tank_monitor_mfg.selectedIndex=0;
	else
	{
		for(var i=0;i<tank_monitor_mfg.options.length;i++)
		{
			if(tank_monitor_mfg.options[i].value==tankMonitor.monitor_MFG)
				tank_monitor_mfg.selectedIndex=i;
		}
	}
	for(var i=tank_monitor_ID.options.length-1;i>=0;i--)//clear tank_monitor_ID options
	{
		tank_monitor_ID.remove(i);	
	}
	for(key in tank_models)//add new options and choose value
	{
		var option = document.createElement('OPTION');
		option.value = key;
		option.text = tank_models[key];
		tank_monitor_ID.options.add(option);
		if(option.value==tank.tank_monitor_ID)
			option.selected=true;
	}

	for(var i=0; i<remote_fill.options.length;i++)
	{
		if(remote_fill.options[i].value==tank.remote_fill)
			remote_fill.selectedIndex=i;
	}
	for(var i=0; i<overfill_alarm.options.length;i++)
	{
		if(overfill_alarm.options[i].value==tank.overfill_alarm)
			overfill_alarm.selectedIndex=i;
	}
	for(var i=0; i<pump_provided.options.length;i++)
	{
		if(pump_provided.options[i].value==tank.pump_provided)
			pump_provided.selectedIndex=i;
	}
	document.getElementById('unit_type').selectedIndex=0;
	
	for(var i=product_ID.options.length-1;i>=0;i--)//clear product_ID options
	{
		product_ID.remove(i);	
	}
	for(key in products)//add new options and choose value
	{
		var option = document.createElement('OPTION');
		option.value = key;
		option.text = products[key];
		product_ID.options.add(option);
		if(option.value==tank.product_ID)
			option.selected=true;
	}
	
	for(var i=0;i<product_category.options.length;i++)
	{
		if(product_category.options[i].value==productCategory)
			product_category.selectedIndex=i;
	}
}

function changeStatus(domain, status)
{
	if(domain==DOMAIN.DETAIL)
	{
		sitedetailStatus=status;
	}
	else if(domain==DOMAIN.PROFILE)
	{
		siteprofileStatus=status;
	}
	else if(domain==DOMAIN.TANK)
	{
		tankStatus=status;
	}
}

/*
* disable the gate_opens and gate_closes fields when isGated is false
* vice versa
*/
function updateGate(isGated)
{
	var prefix = '<?php echo get_class(Sites::model()).'_'; ?>';
	if(isGated=='1')
	{
		document.getElementById(prefix+'gate_opens').disabled=false;
		document.getElementById(prefix+'gate_closes').disabled=false;
	}
	else if(isGated=='0')
	{
		document.getElementById(prefix+'gate_opens').disabled=true;
		document.getElementById(prefix+'gate_closes').disabled=true;
	}
}

/*
* disable the security_code fields when isPremise is false
* vice versa
*/
function updateSecurity(isPremise)
{
	var prefix = '<?php echo get_class(Sites::model()).'_'; ?>';
	if(isPremise=='1')
	{
		document.getElementById(prefix+'security_code').disabled=false;
	}	
	else if(isPremise=='0')
	{
		document.getElementById(prefix+'security_code').disabled=true;		
	}
}

/*
* called when one particular site is selected
*/
function updateOnSite(data)
{
	clickOnSite(false, data[0], data[1]);
}

/*
* ifDisplayTank: if displaying the tank info
*/
function clickOnSite(ifDisplayTank, site, tools)
{
	if(previousSiteID==0)//no site is selected before
	{
		previousSiteID=site.site_ID;
		displayTank(false);
		fillSiteInfo(site, tools);
		document.getElementById('details_site_ID_field').value=site.site_ID;
		document.getElementById('profile_site_ID_field').value=site.site_ID;
		$('#msg-header').hide();
		$('#msg-header').html('');
		updateGate(site.gated);
		updateSecurity(site.security_on_premises);
		siteprofileStatus=STATUS.COMMITTED;
		sitedetailStatus=STATUS.COMMITTED;
	}
	else if(previousSiteID!=site.site_ID)//click on a new site tab
	{
		var abandon=false;
		var message="";
		if(siteprofileStatus==STATUS.CHANGED)
		{
			message+="site-profile is changed\r\n";
		}
		if(sitedetailStatus==STATUS.CHANGED)
		{
			message+="site-details is changed\r\n";
		}
		if(tankStatus==STATUS.CHANGED)
		{
			message+="tank-details is changed\r\n";
		}
		if(message!="")//client has changed some fields
		{
			abandon=window.confirm(message+"Do you want to abandon these changes?");
			if(abandon)
			{
				previousSiteID=site.site_ID;
				displayTank(false);
				fillSiteInfo(site, tools);
				document.getElementById('details_site_ID_field').value=site.site_ID;
				document.getElementById('profile_site_ID_field').value=site.site_ID;
				$('#msg-header').hide();
				$('#msg-header').html('');
				updateGate(site.gated);
				updateSecurity(site.security_on_premises);
				siteprofileStatus=STATUS.COMMITTED;
				sitedetailStatus=STATUS.COMMITTED;
			}
		}
		else
		{
			previousSiteID=site.site_ID;
			displayTank(false);
			fillSiteInfo(site, tools);
			document.getElementById('details_site_ID_field').value=site.site_ID;
			document.getElementById('profile_site_ID_field').value=site.site_ID;
			$('#msg-header').hide();
			$('#msg-header').html('');
			updateGate(site.gated);
			updateSecurity(site.security_on_premises);
			siteprofileStatus=STATUS.COMMITTED;
			sitedetailStatus=STATUS.COMMITTED;
		}
	}
}

/*
* called when one particular site is selected
*/
function updateOnTank(data)
{
	clickOnTank(data[0], data[1], data[2], data[3], data[4], data[5], data[6]);
}

/*
* ifDisplayTank: if displaying the tank info
*/
function clickOnTank(site, tank, tankMonitor, tank_models, tools, products, productCategory)
{
	if(previousTankID!=tank.tank_ID)//select another tank
	{
		var abandon=false;
		var message="";
		if(previousSiteID==site.site_ID)//site remains the same
		{
			if(tankStatus==STATUS.CHANGED)
			{
				message+="tank-details is changed\r\n";
			}
		}
		else
		{
			if(siteprofileStatus==STATUS.CHANGED)
			{
				message+="site-profile is changed\r\n";
			}
			if(sitedetailStatus==STATUS.CHANGED)
			{
				message+="site-details is changed\r\n";
			}
			if(tankStatus==STATUS.CHANGED)
			{
				message+="tank-details is changed\r\n";
			}
		}
		if(message!="")//the user has changed something
		{
			abandon=window.confirm(message+"Do you want to abandon these changes?");
			if(abandon)
			{
				if(previousSiteID!=site.site_ID)
				{
					previousSiteID=site.site_ID;
					fillSiteInfo(site, tools);
				}
				previousTankID=tank.tank_ID;
				displayTank(true);
				fillTankInfo(tank, tankMonitor, tank_models, products, productCategory);
				document.getElementById('details_site_ID_field').value=site.site_ID;
				document.getElementById('profile_site_ID_field').value=site.site_ID;
				document.getElementById('tank_ID_field').value=tank.tank_ID;
				$('#msg-header').hide();
				$('#msg-header').html('');
				tankStatus=STATUS.COMMITTED;
			}
		}
		else//all the changes are committed, display the new tank
		{
			previousSiteID=site.site_ID;
			fillSiteInfo(site, tools);
			
			previousTankID=tank.tank_ID;
			displayTank(true);
			fillTankInfo(tank, tankMonitor, tank_models, products, productCategory);
			document.getElementById('details_site_ID_field').value=site.site_ID;
			document.getElementById('profile_site_ID_field').value=site.site_ID;
			document.getElementById('tank_ID_field').value=tank.tank_ID;
			$('#msg-header').hide();
			$('#msg-header').html('');
			tankStatus=STATUS.COMMITTED;
		}
	}
	else
	{
		displayTank(true);
	}
}

/*
* check status of the 'status' variables
* confirm with the user if to abandon changes and jump to the given url
* url: the url that will jump to
* element: the element that been clicked
*/
function checkStatus(element, url)
{
	var abandon=false;
	var message="";
	if(siteprofileStatus==STATUS.CHANGED)
	{
		message+="site-profile is changed\r\n";
	}
	if(sitedetailStatus==STATUS.CHANGED)
	{
		message+="site-details is changed\r\n";
	}
	if(tankStatus==STATUS.CHANGED)
	{
		message+="tank-details is changed\r\n";
	}
	if(message!="")
	{
		abandon=window.confirm(message+"Do you want to abandon these changes?");
		if(abandon)
			element.href=url;
		else
			element.href='#';
	}
}

function updateProfileStatus(data)
{
	if(data=='profile-success')
	{
		siteprofileStatus=STATUS.COMMITTED;
		$('#msg-header').show();
		$('#msg-header').html('Site Profile updated successfully.');
	}
	else
	{
		$('#msg-header').html('');
	}
}

function updateDetailsStatus(data)
{
	if(data=='details-success')
	{
		sitedetailStatus=STATUS.COMMITTED;
		$('#msg-header').show();
		$('#msg-header').html('Site Details updated successfully.');
	}
	else
	{
		$('#msg-header').html('');
	}
}

function updateTankStatus(data)
{
	if(data=='tank-success')
	{
		tankStatus=STATUS.COMMITTED;
		$('#msg-header').show();
		$('#msg-header').html('Tank Details updated successfully.');
		document.getElementById('capacity-label').innerHTML='';
	}
	else
	{
		$('#msg-header').html('');
		document.getElementById('capacity-label').innerHTML=data['capacity'];
	}
}

function addHomeEvent()
{
	document.getElementById("ms-links4").firstChild.onclick=function(){
		checkStatus(this, '<?php echo Yii::app()->request->baseUrl;?>/landing/buyer');
	}
	document.getElementById("ms-links6").firstChild.onclick=function(){
		checkStatus(this, '<?php echo Yii::app()->request->baseUrl;?>/landing/buyer');
	}
}
addHomeEvent();

var selectedTankID=0;
var selectedElement;
var selectedTankName;

function selectTank(event, element, tankID, siteID, tankName) {
	$("#ms-submit2").html('<input type="image" value="submit" name="yt4" id="yt4" src="<?php echo Yii::app()->request->baseUrl; ?>/images/submit5.jpg" type="image" />');
	$('li ul li a').css('background-color','#DCDDDE');
	$(event.target).css('background-color','#B8B8B8');
	selectedTankID=tankID;
	selectedElement=element;
	selectedTankName=tankName;
	
	$.ajax({
	       url: '<?php echo CController::createUrl('mySites/tankinfo');?>',
	       type: 'post',
	       dataType: 'json',
	       data: {tankID:tankID,siteID:siteID},
	       success: updateOnTank
	});
}

function clickOnAddSite() {	
	clearSite();
	clearTank();
	displayTank(false); //hide tank details
	$('#msg-header').show();
	$('#msg-header').html('Please fill out the following site information and press the submit button to add the site..');
	$("#ms-submit2").html('<div onclick="addSite()" style="cursor: pointer;"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/submit5.jpg" type="image" /></div>');
}

function addSite() {
	$.ajax({
	       url: '<?php echo CController::createUrl('mySites/addsite');?>',
	       type: 'post',
	       dataType: 'json',
	       data: {site_name:$("input=[name='Sites[site_name]']").val(),
		    		address1:$("input=[name='Sites[address1]']").val(),
				   	address2:$("input=[name='Sites[address2]']").val(),
				   	county:$("input=[name='Sites[county]']").val(),
				   	city:$("input=[name='Sites[city]']").val(),
				   	state:$("input=[name='Sites[state]']").val(),
				   	zip:$("input=[name='Sites[zip]']").val(),
		   			home_rack_ID:$("input=[name='Sites[home_rack_ID]']").val()},
	       success: addSiteResult
	});
}

function addSiteResult(data) {
	if(data=='add-site-success')
	{
		$('#msg-header').show();
		$('#msg-header').html('Site has been added.');
	}
	else if (data=='add-site-fail') {
		$('#msg-header').show();
		$('#msg-header').html('Site exists already.');
	}
	else {
		$('#msg-header').show();
		$('#msg-header').html('Unable to add site.');
	}
}

//clears Site profile fields
function clearSite() {
	$("#site-details2 input").val('');
}
</script>

<div id="my-sites">

<div id="my-sites-contents">

<div id="mysite-left">
<div id="mysite-head-left">my sites</div>

<div class="box">
<div class="box-contents" style="min-height:350px;">

<div class="box-top">
    <ul class="box-buttons">
        <li><a href="#" onclick="clickOnAddSite()"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/addsite2.gif" alt="" /></a></li>
        <li><a href="#"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/add-tank.gif" alt="" /></a></li>
    </ul>
</div> <!-- End Box Top -->  

<div id="mysite-links">
    <ul id="sub-nav">
<?php
foreach(array_keys($sitesArray) as $site_ID)
{
	echo "<li>";
 	echo CHtml::button($site_ID, array('id'=>$site_ID, 'style'=>'display:none', 'ajax'=>array(
							'type'=>'POST',
							'url'=>CController::createUrl('mySites/siteinfo'),
							'success'=>'updateOnSite',
							'dataType'=>'json',
							'data'=>"ajax=".$site_ID,
						),));
	echo CHtml::link($sitesArray[$site_ID][0], '#', array(
					'onclick'=>"document.getElementById('".$site_ID."').click()",
					));
	echo "<ul>";
	foreach($sitesArray[$site_ID][1] as $tank)
	{
		if ($tank['active'] != 0) {
			echo "<li>";
			
			echo '<a href="#" onclick="return selectTank(event, this, '.$tank['tank_ID'].', '.$site_ID.', \''.$tank['tank_name'].'\');">Tank '.$tank['tank_name'].'</a>';
			
			echo "</li>";
		}
	}
	echo "</ul></li>";
}
?>
    </ul>
</div><!-- End My Site Links -->

</div><!-- End Box Contents-->
</div><!-- End Box -->
</div><!-- End Mysite Left -->

<div id="mysite-right">
<div id="ms-right-contents">

<div id="site-profile-area" style='display:block'>
<?php
	$site_profile=new Sites;
	$site_profile->scenario='update-profile';
	$this->renderPartial('profile', array('site'=>$site_profile, 'toolsArray'=>$toolsArray)); 
?>
</div>

<div id="racknetwork-area" style='display:none'>
<?php $this->renderPartial('racknetwork', array('rack'=>new Racks)); ?>
</div>

<div id="sitedetails-area" style='display:none'>
<?php 
	$site_details=new Sites;
	$site_details->scenario='update-details';
	$this->renderPartial('details', array('site'=>$site_details)); 
?>
</div>



<div id="sd-menu">
<div class="sd-navi">
    <ul>
        <li name="tabs" class="sd1 sd-active1"><a href="#" title="Site Profile" onclick='displayProfile(this)'>Site Profile</a></li>
    	<!-- <li name="tabs" class="sd2"><a href="#" title="Rack Network" onclick='displayRackNetwork(this)'>Rack Network</a></li> -->
        <li name="tabs" class="sd2"><a href="#" title="Site Details" onclick='displaySiteDetails(this)'>Site Details</a></li>
    </ul>
</div>
</div><!-- End SD Menu -->

</div><!-- End Mysite Right Contents -->
</div><!-- End Mysite Right -->


</div><!-- End My Sites Contents -->
</div><!-- End My Sites -->

<div id="my-sites-ch">My Site Character</div>